package com.example.compose

import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

@Preview
@Composable
private fun TextFieldState() {
    val viewModel = viewModel<SignUpViewModel>()
    Column {
        Text(text = "SIGNUP")
        OutlinedTextField(
            value = viewModel.username,
            onValueChange = { viewModel.updateUsername(it) },
            isError = viewModel.usernameError
        )
        Button(onClick = { /*TODO*/ }) {
            Text(text = "确定")
        }
        val usernameError = viewModel.usernameError
        if (usernameError) {
            Text(text = "用户名错误", color = Color(0xFFC51162))
        }
    }
}

class SignUpViewModel : ViewModel() {
    var username by mutableStateOf("")
        private set

    val usernameError by derivedStateOf {
        username.length < 8
    }

    fun updateUsername(input: String) {
        viewModelScope.launch {
            username = input
        }
    }
}